import { Injectable, UnauthorizedException } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { UserService } from "../user/user.service";

@Injectable()
export class AuthService {
	constructor(
		private userService: UserService,
		private jwtService: JwtService
	) {}

	async validateUser(username: string, password: string): Promise<any> {
		const user = await this.userService.validateUser(username, password);
		if (!user) {
			throw new UnauthorizedException("用户名或密码不正确");
		}
		return user;
	}

	async login(user: any) {
		const payload = { username: user.username, sub: user.id };
		return {
			code: 200,
			message: "登录成功",
			data: {
				token: this.jwtService.sign(payload),
				user: {
					id: user.id,
					username: user.username,
					nickname: user.nickname,
					points: user.points,
					role: user.role,
				},
			},
		};
	}

	async register(createUserDto: any) {
		const user = await this.userService.create(createUserDto);
		const { password, ...result } = user;
		return this.login(result);
	}
}
